package com.qingsong.component;

import cn.hutool.json.JSONUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import com.qingsong.result.Result;

@RestControllerAdvice("com.qingsong.controller")
public class ResultAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        // 放行到 beforeBodyWrite() 方法
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        // 若Jackson使用字符串转换器，使用JSON封装一下再直接返回字符串，避免爆发转换异常
        if (aClass == StringHttpMessageConverter.class) {
            return JSONUtil.toJsonStr(o);
        }
        // 若返回值已经是Result类型则直接返回
        if (o instanceof Result) {
            return o;
        }
        // 统一将Controller的返回值封装为Result类型
        return new Result<>(o);
    }
}